package com.alan.springbootwp.util;

import com.alan.springbootwp.model.AccessToken;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Alan
 * @Description 获取微信token
 * @date 2020年04月21日 14:54
 */
@Slf4j
public class TokenUtil {

    private static AccessToken accessToken = null;

    public static AccessToken getAccessToken() {

        if (accessToken != null) {
            long curTimestamp = System.currentTimeMillis();
            long timestamp = accessToken.getTimestamp();
            long diff = (curTimestamp - timestamp) / 1000 + 500;
            if (diff < accessToken.getExpiresIn()) {
                // * 未过期返回当前的accessToken
                return accessToken;
            }
        }
        String requestUrl = WeChatConstant.ACCESS_TOKEN_URL.replace("APPID", WeChatConstant.APPID).replace("APPSECRET", WeChatConstant.APPSECRET);
        JSONObject jsonObject = HttpUtil.sendRequest(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setAccessToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
                accessToken.setTimestamp(System.currentTimeMillis());
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                try {
                    log.error("获取token失败 errcode:{} errmsg:{}" + jsonObject.getInteger("errcode") + jsonObject.getString("errmsg"));
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return accessToken;
    }
}
